﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HalconDotNet;

namespace Winform_Halcon_OCR
{
    public partial class Form1 : Form
    {
        HObject ho_ImageTest;
        HObject ho_Gray_Image;
        HObject ho_testwordregion;
        HObject ho_ConnectedwordRegions;
        HObject ho_SelectedwordRegions;
        HObject ho_SortedRegions2;
        HTuple hv_Number;
        HTuple hv_OCRHandle;
        HTuple hv_Class;
        HTuple hv_Confidence;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "所有图片|*.bmp;*.jpg";
            openFileDialog.Title = "加载图片";
            openFileDialog.ReadOnlyChecked = true;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                HOperatorSet.ReadImage(out ho_ImageTest, openFileDialog.FileName);
                HTuple width;
                HTuple height;
                HOperatorSet.GetImageSize(ho_ImageTest, out width, out height);
                HOperatorSet.SetPart(hWindowControl1.HalconWindow, 0, 0, height - 1, width - 1);
                HOperatorSet.SetColor(this.hWindowControl1.HalconWindow, "green");
                HOperatorSet.DispObj(ho_ImageTest, hWindowControl1.HalconWindow);
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            //转灰度
            HOperatorSet.Rgb1ToGray(ho_ImageTest, out ho_Gray_Image);
            //阈值分割
            HOperatorSet.Threshold(ho_Gray_Image, out ho_testwordregion, 125, 255);
            //连通区域
            HOperatorSet.Connection(ho_testwordregion, out ho_ConnectedwordRegions);
            //特征提取
            HOperatorSet.SelectShape(ho_ConnectedwordRegions, out ho_SelectedwordRegions, "area", "and", 700, 2500);
            HOperatorSet.SortRegion(ho_SelectedwordRegions, out ho_SortedRegions2, "upper_left", "true", "column");

            HOperatorSet.CountObj(ho_SortedRegions2, out hv_Number);

            HOperatorSet.ReadOcrClassMlp("yszx.omc", out hv_OCRHandle);

            HOperatorSet.DoOcrMultiClassMlp(ho_SortedRegions2, ho_Gray_Image, hv_OCRHandle, out hv_Class, out hv_Confidence);
            HOperatorSet.ClearOcrClassMlp(hv_OCRHandle);

            StringBuilder result = new StringBuilder();
            this.label1.Text = "";
            for (int i = 0; i < hv_Class.Length; i++)
            {
                label1.Text += hv_Class.TupleSelect(i);
            }
        }
    }
}
